<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Http\Service\VoteService;
use App\Model\Advertisement;
use App\Model\ArticleCategories;
use App\Model\ArticleFavorite;
use App\Model\Articles;
use App\Model\Comment;
use App\Model\Follow;
use App\Model\Vote;
use App\Tool\Participle;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Swagger\Annotations as SWG;

class ArticleController extends Controller
{
    /**
     * 前端返回分类和下面的文章
     * @return string
     */
    public function getArticleList()
    {
        $articleCategories = ArticleCategories::orderBy('sort', 'asc')->get();

        $data = [];
        foreach ($articleCategories as $articleCategory) {
            $item = [
                'uuid' => $articleCategory->id,
                'title' => $articleCategory->title,
                'article' => $articleCategory->article,
                'sort' => $articleCategory->sort,
            ];
            $data[] = $item;
        }

        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/get-article/{id}",
     *     tags={"文章相关"},
     *     summary="文章详情",
     *     description="查看文章详情",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Response(
     *          response="200",
     *          description="文章基础信息",
     *          @SWG\Schema(
     *              @SWG\Property(property="uuid", type="integer", description="文章id"),
     *              @SWG\Property(property="title", type="string", description="文章标题"),
     *              @SWG\Property(property="article_category_name", type="string", description="文章所属分类名称"),
     *              @SWG\Property(property="article_category_uuid", type="integer", description="文章所属分类id"),
     *              @SWG\Property(property="content", type="string", description="文章内容"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="pageviews", type="integer", description="浏览量"),
     *              @SWG\Property(property="cresated_at", type="string", format="date", description="发布时间"),
     *              @SWG\Property(property="thumb", type="integer", description="点赞"),
     *              @SWG\Property(property="is_thumb", type="boolean", description="是否点赞"),
     *              @SWG\Property(property="is_favorite", type="boolean", description="是否收藏(登录才有)"),
     *              @SWG\Property(
     *                  property="ad",
     *                  type="object",
     *                  description="广告相关",
     *                  @SWG\Property(property="id", type="integer", description="广告id"),
     *                  @SWG\Property(property="url", type="integer", description="广告url"),
     *                  @SWG\Property(property="image_path", type="integer", description="广告图片"),
     *                  @SWG\Property(property="name", type="integer", description="广告名称"),
     *              ),
     *              @SWG\Property(
     *                  property="author",
     *                  type="object",
     *                  description="作者信息",
     *                  @SWG\Property(property="id", type="integer", description="作者id"),
     *                  @SWG\Property(property="name", type="string", description="作者"),
     *                  @SWG\Property(property="avatar", type="string", description="作者头像"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="作者入驻时间"),
     *                  @SWG\Property(property="is_follow", type="boolean", description="是否关注作者")
     *              ),
     *          )
     *      )
     * )
     */
    public function getArticle($id)
    {
        $article = Articles::where('id', $id)->firstOrFail();

        $article->increment('actual_pageviews', '1');
        $article->increment('pageviews', '1');
        $article->save();

        $data = [
            'uuid' => $article->id,
            'title' => $article->title,
            'article_category_name' => $article->articleCategory?$article->articleCategory->title:'',
            'article_category_uuid' => $article->articleCategory?$article->articleCategory->id:0,
            'content' => str_replace('&nbsp;', ' ', $article->content),
            'cover' => $article->cover,
            'creator' => $article->creator,
            'pageviews' => $article->pageviews,
            'created_at' => $article->created_at->format('Y-m-d H:i:s'),
            'thumb' => $article->thumb,
            'is_thumb' => false
        ];
        // 自媒体作者信息
        $media_user= DB::table("media_users")->where("id", "=", $article->author)->first();
        $author_info = DB::table('media_user_info')->where('media_user_id', $article->author)->first();
        // 是否关注

        $data['author'] = [
            'id' => $media_user?$media_user->id:'0',
            'name' => $author_info?$author_info->account:'汇营天下官方',
            'avatar' => $author_info?$author_info->avatar:'',
            'created_at' => $author_info?$author_info->created_at:0,
            'is_follow' => false,
            'is_enabled' => $media_user ? $media_user->is_enabled : 0
        ];
        //广告
        if ($article->is_ad == 1) {
            $ad = Advertisement::select("id", 'name', "images", "url")
                ->where("status", 2)
                ->where("survival_begin", "<", Carbon::now())
                ->where("survival_end", ">", Carbon::now())
                ->where("type", 2)
                ->where("cate", $article->article_category_id)
                ->inRandomOrder()
                ->first();

            if ($ad) {
                $data['ad'] = [
                    'id' => $ad->id,
                    'url' => $ad->url,
                    'image_path' => $ad->images,
                    'name' => $ad->name
                ];
            }
        }
        if (Auth::check()) {
            //是否收藏
            $is_favorite = ArticleFavorite::where('user_id', Auth::id())->where('article_id', $id)->first();
            $data['is_favorite'] = $is_favorite == null ? false : true;
            //是否关注作者
            $fo = Follow::where('status',1)->where("media_user_id",$article->author)->where('user_id', Auth::id())->first();
            if ($article->author == 0){
                $fo = false;
            }
            $data['author']['is_follow'] = $fo?true:false;
            //是否点赞
            $v = Vote::where('user_id', Auth::id())->where('type',1)->where('vote',1)->where('target_id', $article->id)->first();
            $data['is_thumb'] = $v?true:false;
        }
        if (Auth::check()){
            //记录用户浏览记录
            $label = DB::table('article_label')->where('id',$article->label_id)->first();
            DB::table("view_article_log")->insert(['u_id'=>Auth::id(), 'a_id'=>$article->id,'title'=>$article->title,'label'=>isset($article->label_id)? $article->label_id:'','label_name'=>$label?$label->name:'','created_at'=>Carbon::now()]);
        }
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/articles/categories",
     *     tags={"文章相关"},
     *     summary="文章分类",
     *     description="文章分类",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="分类列表",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="分类id"),
     *                  @SWG\Property(property="title", type="string", description="分类名"),
     *                  @SWG\Property(property="sort", type="integer", description="排序"),
     *                  @SWG\Property(property="parent_id", type="integer", description="上级分类"),
     *                  @SWG\Property(property="is_modify", type="integer", description="是否允许从自己分类删除"),
     *              )
     *          )
     *      )
     * )
     */
    public function categories(ArticleCategories $articleCategories)
    {
        $categories = Cache::remember('categories', 10, function () use ($articleCategories) {
            return $articleCategories->where("is_enabled",0)->orderBy('sort')->get();
        });

        $data = [];
        foreach ($categories as $category) {
            $data[] = [
                'id' => $category->id,
                'title' => $category->title,
                'sort' => $category->sort,
                'parent_id'  => $category->parent_id,
                'is_modify' => $category->is_modify
            ];
        }
        if (Auth::check()){
            $uc = DB::table("user_category")->where("user_id", Auth::id())->first();
            if (empty($uc)){
                //登录没有数据，插入数据
                $id = collect($data)->pluck('id');
                $id = ArticleCategories::whereIn('id', $id)->where('is_enabled', 0)->pluck('id');
                $id = implode(',', $id->toArray());
                DB::table('user_category')->updateOrInsert(['user_id'=>Auth::id()],['category'=>$id, 'created_at'=>Carbon::now()]);
                return $this->renderJson($data);
            }
            $cate = ArticleCategories::select('id', 'title', 'sort', 'parent_id')->where('is_enabled', 0)->whereIn('id', explode(',', $uc->category))->get();
            return $this->renderJson($cate);
        }
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/articles",
     *     tags={"文章相关"},
     *     summary="分类下所有文章",
     *     description="根据分类id获取下面所属文章",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="cate_id", type="integer", required=true, in="query", description="分类id"),
     *     @SWG\Response(
     *          response="200",
     *          description="分类列表",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="文章或广告id"),
     *                  @SWG\Property(property="title", type="string", description="文章或广告标题"),
     *                  @SWG\Property(property="sub_title", type="string", description="文章短标题"),
     *                  @SWG\Property(property="cover", type="string", description="文章封面"),
     *                  @SWG\Property(property="sort_desc", type="string", description="文章简短简介"),
     *                  @SWG\Property(property="pageview", type="integer", description="文章浏览量"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="文章发布时间"),
     *                  @SWG\Property(property="is_ad", type="boolean", description="是否是广告"),
     *                  @SWG\Property(property="describe", type="string", description="广告简介"),
     *                  @SWG\Property(property="url", type="string", description="广告url"),
     *                  @SWG\Property(property="author", type="string", description="作者"),
     *              )
     *          )
     *      )
     * )
     */
    public function index(Articles $article)
    {
        if (!request()->has('cate_id')) {
            return $this->fail('分类参数错误');
        }
        $cate_id = request('cate_id');

        $articles = $article->where('status', 2)->where('article_category_id', '=', $cate_id)->orderByDesc('created_at')->paginate(request('limit'));
        if (empty($articles)) {
            return $this->renderJson();
        }
        $ad = Advertisement::select("id", 'name', "images", "url")
            ->where("status", 2)
            ->where("survival_begin", "<", Carbon::now())
            ->where("survival_end", ">", Carbon::now())
            ->where("type", 3)
            ->where("cate", $cate_id)
            ->inRandomOrder()
            ->first();
        $data = $articles->toArray();
        $c = count($data['data']);
        $r = mt_rand(0, $c);
        $data['data'] = [];
        foreach ($articles as $k=>$a) {
            if ($k == $r && $ad != null){
                $data['data'][] = [
                    'id' => $ad->id,
                    'title' => $ad->name,
                    'author' => '汇营天下官方',
                    'sub_title' => $ad->describe,
                    'describe' => $ad->describe,
                    'cover' => $ad->images,
                    'sort_desc' => $ad->describe,
                    'pageviews' => '',
                    'created_at' => $ad->created_at,
                    'url' => $ad->url,
                    'is_ad' => true
                ];
                continue;
            }
            $data['data'][] = [
                'id' => $a->id,
                'title' => $a->title,
                'author' => $a->author_info?$a->author_info->account:'汇营天下官方',
                'sub_title' => $a->sub_title,
                'describe' => $a->sub_title,
                'cover' => $a->cover,
                'sort_desc' => mb_substr(strip_tags(html_entity_decode($a->content)), 0, 50),
                'pageviews' => $a->pageviews,
                'created_at' => $a->created_at->format('Y-m-d'),
                'url' => '',
                'is_ad' => false
            ];
        }
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/get-article-relation",
     *     tags={"文章相关"},
     *     summary="获取文章详情推荐文章",
     *     description="获取文章详情推荐文章",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="article_category_uuid", type="integer", required=true, in="query", description="分类id"),
     *     @SWG\Response(
     *          response="200",
     *          description="分类列表",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="文章id"),
     *                  @SWG\Property(property="title", type="string", description="文章标题"),
     *                  @SWG\Property(property="cover", type="string", description="文章封面"),
     *                  @SWG\Property(property="author", type="string", description="作者"),
     *                  @SWG\Property(property="count_comment", type="integer", description="评论量"),
     *              )
     *          )
     *      )
     * )
     */
    public function getArticleRelation(Request $request)
    {
        $data = [];
//        if ($request->ajax()){

        $article_category_uuid = $request->input('article_category_uuid');

        $items = DB::table('articles')->where(['article_category_id' => $article_category_uuid, "is_deleted" => 0, "deleted_at" => null, 'status'=>2])
            ->inRandomOrder()
            ->take(5)
            ->get();
        foreach ($items as $item) {
            $data[] = [
                'id' => $item->id,
                'title' => $item->title,
                'cover' => $item->cover,
                'author' => '平台',
                'count_comment' => Comment::getComments($item->id)->count()
            ];
        }

        return $this->renderJson($data);

//        }
//        return $this->error();
    }

    /**
     * @SWG\Get(
     *     path="/front/articles/recommend",
     *     tags={"文章相关"},
     *     summary="首页推荐分类数据",
     *     description="首页推荐分类数据",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="分类列表",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="文章id"),
     *                  @SWG\Property(property="title", type="string", description="文章标题"),
     *                  @SWG\Property(property="cover", type="string", description="文章封面"),
     *                  @SWG\Property(property="sort_desc", type="string", description="文章简短简介"),
     *                  @SWG\Property(property="pageview", type="integer", description="文章浏览量"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="文章发布时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function recommend()
    {
        //没有登录就随机推荐
        if (!Auth::check()) {
            $items = DB::table('articles')->inRandomOrder()->take(10)->get();
            $data = [];
            foreach ($items as $item) {
                $data[] = [
                    'id' => $item->id,
                    'title' => $item->title,
                    'cover' => $item->cover,
                    'sort_desc' => mb_substr(strip_tags(html_entity_decode($item->content)), 0, 50),
                    'pageviews' => $item->pageviews,
                    'created_at' => $item->created_at
                ];
            }
            return $this->renderJson($data);
        }
        //用户浏览近10条记录文章id
        $history = DB::table('view_article_log')->select('*', DB::raw('count(*) as count'))->where('u_id', Auth::id())->groupBy('a_id')->take(3)->get();

        $p = new Participle(storage_path('dict.json'));
        $dict = [];
        $filter = ['，', ',', '。', '.', '‘', '’', "'", '“', '”', '"', '！', '!', '？', '?', '、', ''];
        //分词
        foreach ($history as $h){
            foreach ($p->getWord($h->title) as $s){
                $str = trim(array_first($s));
                if (!in_array($str, $filter)) {
                    $dict[] = $str;
                }
            }
        }
        //去重
        $dict = array_unique($dict);
        $where = implode('|', $dict);
        $items = DB::table('articles')->where('title', 'REGEXP', $where)->take(10)->get();
        $len = count($items);
        if ($len < 10){
            $rep = DB::table('articles')->inRandomOrder()->take(10 - $len)->get();
            $items = $items->merge($rep);
        }
        return $this->renderJson($items);
    }

    /**
     * @SWG\Post(
     *     path="/front/thumb/article/{id}",
     *     tags={"文章相关"},
     *     summary="给文章点赞",
     *     description="文章点赞",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Response(
     *          response="200",
     *          description="点赞成功"
     *      )
     * )
     */
    public function thumb($id)
    {
        try {
            VoteService::voteUp(1, $id);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        return $this->success();
    }

    /**
     * @SWG\Post(
     *     path="/front/un_thumb/article/{id}",
     *     tags={"文章相关"},
     *     summary="取消文章点赞",
     *     description="取消文章点赞",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Response(
     *          response="200",
     *          description="取消点赞成功"
     *      )
     * )
     */
    public function unThumb($id)
    {
        try {
            VoteService::unVoteUp(1, $id);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        return $this->success();
    }

    /**
     * @SWG\Post(
     *     path="/front/complaint/article/{id}",
     *     tags={"文章相关"},
     *     summary="举报文章",
     *     description="举报文章",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Parameter(name="item", in="formData", required=true, type="string", description="举报内容"),
     *     @SWG\Parameter(name="content", in="formData", required=true, type="string", description="举报附件内容"),
     *     @SWG\Response(
     *          response="200",
     *          description="举报成功"
     *      )
     * )
     */
    public function complaint(Request $request, $id)
    {

        $article = Articles::find($id);
        if (!$article){
            return $this->fail('文章不存在');
        }
        $user = Auth::user();
        $username = '';
        if ($user->cards){
            if ($user->cards->user_name){
                $username = $user->cards->user_name;
            }else{
                if ($user->detail){
                    if ($user->detail->wechat_name){
                        $username = $user->detail->wechat_name;
                    }
                }
            }
        }
        $author_info = DB::table('media_user_info')->where('media_user_id', $article->author)->first();
        DB::table('complaint')->insert([
            'type' => 2,
            'quote' => $article->id,
            'user_id' => $user->id,
            'phone' => $user->phone,
            'username' => $username,
            'target_id' => $article->author,
            'target' => $author_info?$author_info->account:'',
            'item' => $request->input('item'),
            'content' => $request->input('content'),
            'created_at' => Carbon::now()
        ]);
        return $this->success();
    }

    /**
     * @SWG\Get(
     *     path="/front/articles/share/{id}",
     *     tags={"文章相关"},
     *     summary="文章分享埋点",
     *     description="文章分享埋点",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功"
     *      )
     * )
     */
    public function share($id)
    {
        Articles::find($id)->increment('share_num');
        return $this->success();
    }
}
